/*
 * Copyright (C) 2010 Fores Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jp.fores.midori.server.container.impl;

import javax.servlet.ServletConfig;

import jp.fores.midori.core.util.ClassUtil;
import jp.fores.midori.server.container.Container;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * コンテナクラスのSpring実装クラス。<br>
 */
public class SpringContainer implements Container {
	//==========================================================
	//フィールド

	/**
	 * Springのコンテキスト
	 */
	private ApplicationContext appContext = null;


	//==========================================================
	//メソッド

	//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
	//抽象メソッドの実装

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getObject(String name) throws Exception {
		//Springのコンテキストからクラス名に対応するオブジェクトを取得する
		Object component = this.appContext.getBean(ClassUtil.forNameWithCache(name));

		//取得したオブジェクトがApplicationContextAwareの場合
		if (component instanceof ApplicationContextAware) {
			//ApplicationContextAwareにSpringのコンテキストを設定する
			((ApplicationContextAware) component).setApplicationContext(this.appContext);
		}

		//取得したオブジェクトを返す
		return component;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init(ServletConfig config) throws Exception {
		//Springのコンテキストの初期化を行う
		this.appContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void destroy() throws Exception {
		//特に何も行わない
	}
}
